﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration.Claims;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.WebPartPages;
using System.IO;
using System.Web.UI.WebControls;
using System.Web.UI;
using System.Text;
using System.Diagnostics;
using System.Net.Mime;
using System.Reflection;


namespace SPUtilities.ManageGroupsPerUser
{
    public static class SPExtensions
    {   
        /// <summary>
        /// Retorna o email do SPUser, e String.Empty caso esteja em branco.
        /// Para maior clareza nas consultas com LINQ
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public static string GetEmail(this SPUser user)
        {
            if (user != null && user.Email != null)
            {
                return user.Email;
            }
            return String.Empty;
        }

        /// <summary>
        /// Retorna o login do SPUser, e String.Empty caso esteja em branco.
        /// Para maior clareza nas consultas com LINQ
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public static string GetLogin(this SPUser user)
        {
            if (user != null && user.LoginName != null)
            {
                return user.LoginName;
            }
            return String.Empty;
        }

        /// <summary>
        /// Retorna o login do SPUser, e String.Empty caso esteja em branco.
        /// Para maior clareza nas consultas com LINQ
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public static string GetSanitizedLogin(this SPUser user)
        {
            using (new SPMonitoredScope("GetUsernameFromClaim method start"))
            {
                String claimsEncodedUsername = user.LoginName;
                try
                {
                    SPClaimProviderManager spClaimProviderManager = SPClaimProviderManager.Local;
                    if (spClaimProviderManager != null)
                    {
                        if (SPClaimProviderManager.IsEncodedClaim(claimsEncodedUsername))
                        {
                            // return the normal domain/username without any claims identification data
                            return spClaimProviderManager.ConvertClaimToIdentifier(claimsEncodedUsername).SanitizeFolderName();
                        }
                    }
                }
                catch (Exception ex)
                {
                    // You should handle any exceptions in here instead of ignoring them!
                    // Logger.Log("An exception occured in the GetUsernameFromClaim() method");
                    return claimsEncodedUsername.SanitizeFolderName(); // Or just return the original username.
                }
                // Return the original username value if it couldn't be resolved as a claims username
                return claimsEncodedUsername.SanitizeFolderName();
            }
            //if (user != null && user.LoginName != null)
            //{
            //    return user.LoginName.SanitizeFolderName();
            //}
            return String.Empty;
        }

        /// <summary>
        /// Retorna o login do SPUser, Sem claims.
        /// Para maior clareza nas consultas com LINQ
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public static string GetLoginWithoutClaims(this SPUser user)
        {
            using (new SPMonitoredScope("GetUsernameFromClaim method start"))
            {
                String claimsEncodedUsername = user.LoginName;
                try
                {
                    SPClaimProviderManager spClaimProviderManager = SPClaimProviderManager.Local;
                    if (spClaimProviderManager != null)
                    {
                        if (SPClaimProviderManager.IsEncodedClaim(claimsEncodedUsername))
                        {
                            // return the normal domain/username without any claims identification data
                            return spClaimProviderManager.ConvertClaimToIdentifier(claimsEncodedUsername);
                        }
                    }
                }
                catch (Exception ex)
                {
                    // You should handle any exceptions in here instead of ignoring them!
                    // Logger.Log("An exception occured in the GetUsernameFromClaim() method");
                    return claimsEncodedUsername;// Or just return the original username.
                }
                // Return the original username value if it couldn't be resolved as a claims username
                return claimsEncodedUsername;
            }
            
            return String.Empty;
        }

        /// <summary>
        /// Retorna o login do SPUser, Sem claims.
        /// Para maior clareza nas consultas com LINQ
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public static string GetLoginWithoutClaims(this String LoginName)
        {
            using (new SPMonitoredScope("GetUsernameFromClaim method start"))
            {
                String claimsEncodedUsername = LoginName;
                try
                {
                    SPClaimProviderManager spClaimProviderManager = SPClaimProviderManager.Local;
                    if (spClaimProviderManager != null)
                    {
                        if (SPClaimProviderManager.IsEncodedClaim(claimsEncodedUsername))
                        {
                            // return the normal domain/username without any claims identification data
                            return spClaimProviderManager.ConvertClaimToIdentifier(claimsEncodedUsername);
                        }
                    }
                }
                catch (Exception ex)
                {
                    // You should handle any exceptions in here instead of ignoring them!
                    // Logger.Log("An exception occured in the GetUsernameFromClaim() method");
                    return claimsEncodedUsername;// Or just return the original username.
                }
                // Return the original username value if it couldn't be resolved as a claims username
                return claimsEncodedUsername;
            }
           
            return String.Empty;
        }

        public static string GetLoginWithClaims(this String LoginName)
        {
            using (new SPMonitoredScope("GetUsernameFromClaim method start"))
            {
                
                try
                {
                    SPClaimProviderManager spClaimProviderManager = SPClaimProviderManager.Local;
                    if (spClaimProviderManager != null)
                    {
                        if (SPClaimProviderManager.IsEncodedClaim(LoginName))
                        {
                            // return the normal domain/username without any claims identification data
                            return spClaimProviderManager.ConvertIdentifierToClaim(LoginName, SPIdentifierTypes.EncodedClaim).ToEncodedString();
                        }
                    }
                }
                catch (Exception ex)
                {
                    // You should handle any exceptions in here instead of ignoring them!
                    // Logger.Log("An exception occured in the GetUsernameFromClaim() method");
                    return LoginName;// Or just return the original username.
                }
                // Return the original username value if it couldn't be resolved as a claims username
                return LoginName;
            }
            //if (user != null && user.LoginName != null)
            //{
            //    return user.LoginName.SanitizeFolderName();
            //}
            return String.Empty;
        }

        public static string GetCreatorName(this SPListItem item) {
            String CreatorName = String.Empty;
            try {
                CreatorName = item[SPBuiltInFieldId.Author].ToString().Split(new String[] { ";#" }, StringSplitOptions.RemoveEmptyEntries)[1];
            }
            catch { } 
            return CreatorName != String.Empty ? CreatorName : "N/A";
        }

        public static string GetEditorName(this SPListItem item)
        {
            String EditorName = String.Empty;
            try
            {
                EditorName = item[SPBuiltInFieldId.Editor].ToString().Split(new String[] { ";#" }, StringSplitOptions.RemoveEmptyEntries)[1];
            }
            catch { }
            return EditorName != String.Empty ? EditorName : "N/A";
        }

        /// <summary>
        /// Valida se usuário pertence à um certo grupo, à partir de seu ID
        /// </summary>
        /// <param name="web">SPWeb - Site onde o grupo à ser pesquisado se encontra</param>
        /// <param name="GroupName">Nome do grupo</param>
        /// <param name="userId">Id de Usuário</param>
        /// <returns>Grupo contêm usuário ou não</returns>
        public static bool CheckIfGroupContainsUserById(this SPWeb web, String GroupName, Int32 userId) {
            
            try
            {
                SPUser user = web.Groups[GroupName].Users.GetByID(userId);
                if (user != null)
                {
                    //current user is member of this group
                    return true;
                }
            }
            catch
            {
                //current user is not a member of this group                
            }
            return false;
        }
        public static bool CheckIfGroupContainsUser(this SPWeb web, String GroupName, String userName)
        {

            try
            {
                SPUser user = web.EnsureUser(userName);
                SPUser userTry = web.SiteGroups[GroupName].Users.GetByID(user.ID);
                if (user != null)
                {
                    //current user is member of this group
                    return true;
                }
            }
            catch
            {
                //current user is not a member of this group                
            }
            return false;
        }


        /// <summary>
        /// Forja campos 'Editor' e 'Author', para não ficar como 'SYSTEM ACCOUNT'
        /// </summary>
        /// <param name="item"></param>
        /// <param name="user"></param>
        public static void UpdateSetUserAsCreatorAndEditor(this SPListItem item, SPUser user)
        {
            //Item deve ter sido atualizado pelo menos uma vez para funcionar corretamente
            item[SPBuiltInFieldId.Editor] = user;
            item[SPBuiltInFieldId.Author] = user;
            item.UpdateOverwriteVersion();//Somente updateoverwrite version permite forjar o usuário para não pegar conta de sistema.                            
        }

        /// <summary>
        /// Forja campo 'Editor', para não ficar como 'SYSTEM ACCOUNT'
        /// </summary>
        /// <param name="item"></param>
        /// <param name="user"></param>
        public static void UpdateSetUserAsEditor(this SPListItem item, SPUser user)
        {
            //Item deve ter sido atualizado pelo menos uma vez para funcionar corretamente
            item[SPBuiltInFieldId.Editor] = user;
            item.UpdateOverwriteVersion();//Somente updateoverwrite version permite forjar o usuário para não pegar conta de sistema.                                 
        }
    }
}